import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

// 引入store大仓库
import store from '@/store';

// 引入路由组件
const Home = () => import('@/pages/Home');
const Login = () => import('@/pages/Login');
const Register = () => import('@/pages/Register');
const Search = () => import('@/pages/Search');
const Detail = () => import('@/pages/Detail');
const ShopCart = () => import('@/pages/ShopCart');
const Success = () => import('@/pages/AddCartSuccess');
const Trade = () => import('@/pages/Trade');
const Pay = () => import('@/pages/Pay');
const PaySuccess = () => import('@/pages/PaySuccess');
const Center = () => import('@/pages/Center');

const routes = [
	{ path: '/', redirect: '/home' },
	{ path: '/home', component: Home, meta: { show: true } },
	{ path: '/search/:keyword?', component: Search, meta: { show: true }, name: 'search' },
	{ path: '/login', component: Login, meta: { show: false } },
	{ path: '/register', component: Register, meta: { show: false } },
	{ path: '/detail/:skuid?', component: Detail, meta: { show: false }, name: 'detail' },
	{ path: '/shopcart', component: ShopCart, meta: { show: false } },
	{ path: '/success', component: Success, meta: { show: false } },
	{
		path: '/trade',
		component: Trade,
		meta: { show: false },
		// 路由独享守卫
		//只有从购物车点结算，才可以跳转到trade结算页面。（创建订单）
		beforeEnter: (to, from, next) => {
			if (from.path == '/shopcart') {
				next();
			} else {
				next(false);
			}
		}
	},
	{
		path: '/pay',
		component: Pay,
		meta: { show: false },
		// 只有从结算页面，点击提交订单，才可以跳转到pay支付页面。
		beforeEnter: (to, from, next) => {
			if (from.path.indexOf('/trade') > -1) {
				next();
			} else {
				next(false);
			}
		}
	},
	{
		path: '/paysuccess',
		component: PaySuccess,
		meta: { show: false },
		// 只有从pay支付页面，才可以跳转到paysuccess支付成功页面
		beforeEnter: (to, from, next) => {
			if (from.path.indexOf('/pay') > -1) {
				next();
			} else {
				next(false);
			}
		}
	},
	{
		path: '/center',
		component: Center,
		meta: { show: false },
		children: [
			{ path: '/center', redirect: '/center/myorder' },
			{ path: '/center/myorder', component: () => import('@/pages/Center/myOrder.vue') },
			{ path: '/center/grouporder', component: () => import('@/pages/Center/groupOrder.vue') }
		]
	}
];

const router = new VueRouter({
	routes,
	// 滚动到顶部
	scrollBehavior(to, from, savedPosition) {
		return { y: 0 };
	}
	// 在进行路由跳转时，如果用户已经登录，就不能再回登录注册页面
	// 在进行路由跳转时，派发action，获取用户信息
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
	// token
	let token = store.state.user.token;
	// 有没有用户信息
	let name = store.state.user.userInfo.name;
	// 有token代表用户登录了
	if (token) {
		// 登录了就不能再进入登录注册页面
		if (to.path == '/login' || to.path == '/register') {
			next(false);
		} else {
			// 登录了，去的不是登录注册页面
			// 登录了，且有用户名就放行
			if (name) {
				next();
			} else {
				// 如果没有用户名，就派发action去获取用户信息
				store
					.dispatch('getUserInfo')
					.then(() => {
						next();
					})
					.catch(() => {
						// token失效了，获取不到用户的信息，会走catch，此时要清除token，重新登录
						store.dispatch('logOut').then(() => {
							next('/login');
						});
					});
			}
		}
	} else {
		// 没有登录,不能去交易相关页面，不能去支付相关【pay，paysuccess】，个人中心
		// 去上面这些页面之前，需要登录
		let toPath = to.path;
		if (toPath.indexOf('/trade') !== -1 || toPath.indexOf('/pay') !== -1 || toPath.indexOf('/center') !== -1) {
			// 存储想要去的页面路由，登录之后跳转到这个页面
			router.push(`/login?redirect=${to.path}`).catch(() => {});
		} else {
			next();
		}
	}
});

export default router;
